package cn.zhj.springboot.filter;

import cn.zhj.springboot.config.AuthProperties;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class MyFilter implements Filter {

    @Autowired
    private AuthProperties authProperties;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("【Filter】初始化");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        // 获取请求路径
        String path = httpRequest.getRequestURI();
        // 认证配置是否放行
        if (authProperties.isEnable()) {
//            System.out.println("【认证配置】已启用");
            if (authProperties.getExcludePaths().contains(path)) {
                chain.doFilter(request, response); // 放行
                return;
            }
        } else {
//            System.out.println("【认证配置】已禁用");
        }

        HttpServletRequest req = (HttpServletRequest) request;
//        System.out.println("【Filter】请求进入: " + req.getRequestURI());

        // 继续执行后续流程（包括 Interceptor 和 Controller）
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
//        System.out.println("【Filter】销毁");
    }
}
